<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\widgets\LinkPager;

$this->title = 'datalist';
?>
  <link rel="stylesheet" href="css/font.css"/>
  <style>
    .jOrgChart {padding:10px;}
    .jOrgChart .line {height: 20px;width:4px;}
    .jOrgChart .down {background-color: #3c8dbc;margin:0 auto;}
    .jOrgChart .top {border-top  : 3px solid #3c8dbc;}
    .jOrgChart .left {border-right: 2px solid #3c8dbc;}
    .jOrgChart .right { border-left: 2px solid #3c8dbc;  }
    .jOrgChart td {text-align: center;vertical-align : top;padding : 0; }
    .jOrgChart .node {background-color: #3c8dbc; display: inline-block; width: 96px;height: 60px;z-index : 10;border-radius: 8px;border: 3px solid #FFF;}
    .jOrgChart .node span{position:relative;display:block;width:100%;height:100%;text-align:center;line-height:60px;color:#FFF;font-size:14px;}
    .jOrgChart  .node span b{position:absolute;top:0;left:0;right:0;bottom:0;z-index:10;background:#FFF;border:1px solid #3c8dbc;border-radius:5px;color:#3c8dbc;font-weight:normal;font-size:24px;display:none;}
    .drag-active { border-style: dotted !important;}
    .drop-hover { border-style: solid !important; border-color: #E05E00 !important;}
  </style>

  <section></section>
  <div id="chart" class="orgChart"></div>
  <script src="plugins/jquery.js"></script>
  <script src="plugins/jquery-ui.js"></script>
  <script type="text/javascript" src="plugins/prettify.js"></script>

  <script>
    $(function(){
          $.fn.jOrgChart=function(options) {
          var opts = $.extend({}, $.fn.jOrgChart.defaults, options);
          var $appendTo = $(opts.chartElement);
          // build the tree
          $this = $(this);
          var $container = $("<div class='" + opts.chartClass + "'/>");
          if($this.is("ul")) {
            buildNode($this.find("li:first"), $container, 0, opts);
          }
          else if($this.is("li")) {
            buildNode($this, $container, 0, opts);
          }
          $appendTo.append($container);
          if(opts.dragAndDrop){
              $('div.node').draggable({
                  //cursor      : 'move',
                  distance    : 40,
                  helper      : 'clone',
                  opacity     : 0.8,
                  revert      : 'invalid',
                  revertDuration : 100,
                  snap        : 'div.node.expanded',
                  snapMode    : 'inner',
                  stack       : 'div.node'
              });

              $('div.node').droppable({
                  accept      : '.node',
                  activeClass : 'drag-active',
                  hoverClass  : 'drop-hover'
              });
            // Drag start event handler for nodes
            $('div.node').bind("dragstart", function handleDragStart( event, ui ){
              var sourceNode = $(this);
              sourceNode.parentsUntil('.node-container')
                         .find('*')
                         .filter('.node')
                         .droppable('disable');
            });
            $('div.node').bind("dragstop", function handleDragStop( event, ui ){
              $(opts.chartElement).children().remove();
              $this.jOrgChart(opts);
            });
            $('div.node').bind("drop", function handleDropEvent( event, ui ) {
              var targetID = $(this).data("tree-node");
              var targetLi = $this.find("li").filter(function() { return $(this).data("tree-node") === targetID; } );
              var targetUl = targetLi.children('ul');
              var sourceID = ui.draggable.data("tree-node");
              var sourceLi = $this.find("li").filter(function() { return $(this).data("tree-node") === sourceID; } );
              var sourceUl = sourceLi.parent('ul');
              if (targetUl.length > 0){
                targetUl.append(sourceLi);
              } else {
                targetLi.append("<ul></ul>");
                targetLi.children('ul').append(sourceLi);
              }
              if (sourceUl.children().length === 0){
                sourceUl.remove();
              }
            });
          }
        };
        $.fn.jOrgChart.defaults = {
          chartElement : 'body',
          depth      : -1,
          chartClass : "jOrgChart",
          dragAndDrop: false
        };
        var nodeCount = 0;
        function buildNode($node, $appendTo, level, opts) {
          var $table = $("<table cellpadding='0' cellspacing='0' border='0'/>");
          var $tbody = $("<tbody/>");
          var $nodeRow = $("<tr/>").addClass("node-cells");
          var $nodeCell = $("<td/>").addClass("node-cell").attr("colspan", 2);
          var $childNodes = $node.children("ul:first").children("li");
          var $nodeDiv;
          if($childNodes.length > 1) {
            $nodeCell.attr("colspan", $childNodes.length * 2);
          }
          var $nodeContent = $node.clone()
                                  .children("ul,li")
                                  .remove()
                                  .end()
                                  .html();
          nodeCount++;
          $node.data("tree-node", nodeCount);
          $nodeDiv = $("<div>").addClass("node")
                                           .data("tree-node", nodeCount)
                                           .append($nodeContent);
          //if ($childNodes.length > 0) {
          //  $nodeDiv.click(function() {
          //      var $this = $(this);
          //      var $tr = $this.closest("tr");
          //      if($tr.hasClass('contracted')){
          //        $this.css('cursor','n-resize');
          //        $tr.removeClass('contracted').addClass('expanded');
          //        $tr.nextAll("tr").css('visibility', '');
          //        $node.removeClass('collapsed');
          //      }else{
          //        $this.css('cursor','s-resize');
          //        $tr.removeClass('expanded').addClass('contracted');
          //        $tr.nextAll("tr").css('visibility', 'hidden');
          //
          //        $node.addClass('collapsed');
          //      }
          //    });
          //}
          $nodeCell.append($nodeDiv);
          $nodeRow.append($nodeCell);
          $tbody.append($nodeRow);
          if($childNodes.length > 0) {
            //$nodeDiv.css('cursor','n-resize');
            if(opts.depth == -1 || (level+1 < opts.depth)) {
              var $downLineRow = $("<tr/>");
              var $downLineCell = $("<td/>").attr("colspan", $childNodes.length*2);
              $downLineRow.append($downLineCell);
              $downLine = $("<div></div>").addClass("line down");
              $downLineCell.append($downLine);
              $tbody.append($downLineRow);
              var $linesRow = $("<tr/>");
              $childNodes.each(function() {
                var $left = $("<td>&nbsp;</td>").addClass("line left top");
                var $right = $("<td>&nbsp;</td>").addClass("line right top");
                $linesRow.append($left).append($right);
              });
              $linesRow.find("td:first")
                          .removeClass("top")
                       .end()
                       .find("td:last")
                          .removeClass("top");
              $tbody.append($linesRow);
              var $childNodesRow = $("<tr/>");
              $childNodes.each(function() {
                 var $td = $("<td class='node-container'/>");
                 $td.attr("colspan", 2);
                 // recurse through children lists and items
                 buildNode($(this), $td, level+1, opts);
                 $childNodesRow.append($td);
              });
            }
            $tbody.append($childNodesRow);
          }
          if ($node.attr('class') != undefined) {
              var classList = $node.attr('class').split(/\s+/);
              $.each(classList, function(index,item) {
                  if (item == 'collapsed') {
                      $nodeRow.nextAll('tr').css('visibility', 'hidden');
                          $nodeRow.removeClass('expanded');
                          $nodeRow.addClass('contracted');
                          //$nodeDiv.css('cursor','s-resize');
                  } else {
                      $nodeDiv.addClass(item);
                  }
              });
          }
          $table.append($tbody);
          $appendTo.append($table);
          $nodeDiv.children('a').click(function(e){
              e.stopPropagation();
          });
      };
   
      var url = "<?= Url::toRoute('department/departs')?>";
      var _csrf ="<?= Yii::$app->request->getCsrfToken()?>";
      $.ajax({
        url:url,
        type:'GET',
        dataType:'json',
        data: {
          _csrf:_csrf
        },
        success: function(result){

          var showlist = $("<ul id='org' style='display:none'></ul>");
          showall(result, showlist);
          $("section").append(showlist);
          $("#org").jOrgChart( {
            chartElement : '#chart',
            dragAndDrop : false 
          });
          var html="<b class='change iconfont'>&#xe645;</b>";
          $(".jOrgChart  .node span").append(html);
        },
        error:function(){
          console.log("error");
        }
      });
    });

    function showall(menu_list, parent) {
      $.each(menu_list, function(index, val) {
        if(val.childrens.length > 0){
          var li = $("<li></li>");
          li.append("<span did='"+val.id+"'>"+val.name+"</span>").append("<ul></ul>").appendTo(parent);
          showall(val.childrens, $(li).children().eq(1));
        }else{
          $("<li></li>").append("<span did='"+val.id+"'>"+val.name+"</span>").appendTo(parent);
        }
      });
    }

    $("body").on("mouseover mouseout",".node-cell .node span",function(event){
      if(event.type == "mouseover"){
        $(this).children("b").show();
      }else if(event.type == "mouseout"){
        $(this).children("b").hide();
      }
    });

    $("body").on("click",".node-cell .node span",function(){
        var did = $(this).attr('did');
        window.location.href = "http://localhost/advanced/backend/web/index.php?r=department/create&id="+did;
    }); 
  </script>


